package com.mall.mymall.controller;

import com.mall.mymall.common.Result;
import com.mall.mymall.dao.dto.UserDto;
import com.mall.mymall.dao.entity.Users;
import com.mall.mymall.service.UsersService;
import com.mall.mymall.utils.RedisUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 十里坡
 * @since 2025-03-06
 */
@RestController
@RequestMapping("/users")
public class UsersController {

    @Autowired
    private UsersService usersService;

    @Autowired
    private RedisUtils redisUtils;

    // 查询所有用户
    @GetMapping("/list")
    public List<Users> getAllUsers() {
        return usersService.getAllUsers();
    }

    /**
     * 处理用户登录请求
     *
     * 该方法主要负责验证用户身份信息，并在验证通过后生成JWT令牌
     * 它首先通过AuthenticationManager对用户提供的用户名和密码进行认证
     * 认证通过后，使用JWTUtil生成JWT令牌，并将该令牌与用户信息一同返回给客户端
     *
     * @param userDto 用户登录信息，包括用户名和密码
     * @return 登录结果，包括用户信息和JWT令牌
     */
    @PostMapping("/login")
    public Result<Users> login(@RequestBody UserDto userDto, HttpServletResponse response) {
        try {
            Users user = usersService.getUserByUsername(userDto.getUsername());
            if (user != null && user.getPassword().equals(userDto.getPassword())) {
                return Result.success(user);
            }
            return Result.fail("用户名或密码错误");
        } catch (Exception e) {
            return Result.fail("登陆失败");
        }
    }
    @GetMapping("/getUserById/{userId}")
    public Result<Users> getUserById(@PathVariable Integer userId) {
        Users user = usersService.getUserById(userId);
        if (user != null) {
            return Result.success(user);
        }
        return Result.fail("用户不存在");
    }

    @PutMapping("/update")
    public Result<Users> updateUser(@RequestBody Users user) {
        Users userById = usersService.getUserById(user.getUserId());
        userById.setEmail(user.getEmail());
        userById.setPhone(user.getPhone());
        usersService.updateById(userById);
        return Result.success(user);
    }


    /**
     * 注册属于写数据库 这里需要注意并发问题
     *
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    public Result<Users> register(@RequestBody UserDto userDto) {
        try {
            return Result.success(usersService.register(userDto));
        } catch (Exception e) {
            return Result.fail(e.getMessage());
        }
    }


    @GetMapping("/getUserByUsername/{username}")
    public Result<String> getUserByUsername(@PathVariable String username) {
        String s = redisUtils.loadUser(username);
        if (s != null) {
            return Result.success(s);
        }
        return Result.fail("用户不存在");
    }
}